package com.zhengxiang.onlinexamination.controller;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhengxiang.onlinexamination.base.AjaxResult;
import com.zhengxiang.onlinexamination.base.Constants;
import com.zhengxiang.onlinexamination.entity.LoginUser;
import com.zhengxiang.onlinexamination.entity.LoginBody;
import com.zhengxiang.onlinexamination.entity.SysMenu;
import com.zhengxiang.onlinexamination.entity.SysUser;
import com.zhengxiang.onlinexamination.service.*;
import com.zhengxiang.onlinexamination.utils.MessageUtils;
import com.zhengxiang.onlinexamination.utils.SecurityUtils;
import com.zhengxiang.onlinexamination.utils.WxUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.*;

/**
 * @author zhengxiang
 * @data 2023/3/9 9:09
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录后台账号
     */
    @RequestMapping("/logAccount")
    public AjaxResult logAccount(@RequestBody LoginBody loginBody) {
        Map<String, Object> map = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUserAccount(), loginBody.getUserPassword(), loginBody.getCode(),
                loginBody.getUuid());
        map.put(Constants.TOKEN, token);
        return AjaxResult.success(map);
    }
    /**
     * 微信登录
     */
    @PostMapping("/logWx")
    public AjaxResult logWx(@RequestBody LoginBody loginBody) {
        Map<String, Object> map = new HashMap<>();
        //获取微信用户
        QueryWrapper<SysUser> q = new QueryWrapper<>();
        q.lambda().eq(SysUser::getUnionId, loginBody.getUnionId());
        SysUser sysUser = sysUserService.getOne(q);
        //获取微信用户信息
        String url ="https://api.weixin.qq.com/sns/jscode2session?appid";
        Map<String,Object> params = new HashMap<>();
        params.put("appid", WxUtils.API_KEY);
        params.put("secret",WxUtils.SECRET_KEY);
        params.put("js_code",loginBody.getWxCode());
        String s = HttpUtil.get(url);
        System.out.println(s);
        String token ="";
        if(Objects.nonNull(sysUser)){
            // 生成令牌
             token = loginService.login(loginBody.getUserAccount(), "123456", loginBody.getCode(),
                    loginBody.getUuid());
        }else{
            //去注册
             sysUser =  sysUserService.addWxUser(loginBody.getUnionId());
             sysUser.setUserPassword(SecurityUtils.encryptPassword(sysUser.getUserPassword()));
            // 生成令牌
             token = loginService.login(sysUser.getUserAccount(), "123456", loginBody.getCode(),
                    loginBody.getUuid());
        }
        map.put(Constants.TOKEN, token);
        return AjaxResult.success(map);
    }
    /**
     * 生成token
     */
    @PostMapping("/getToken")
    public AjaxResult getToken(@RequestBody LoginBody loginBody) {
        Map<String, Object> map = new HashMap<>();
//        根据手机号获取用户
        QueryWrapper<SysUser> q = new QueryWrapper<>();
        q.lambda().eq(SysUser::getPhoneNumber, loginBody.getPhoneNumber());
        SysUser sysUser = sysUserService.getOne(q);
//        创建token
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
        String token = tokenService.createToken(loginUser);
        map.put(Constants.TOKEN, token);
        return AjaxResult.success(map);
    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
    public AjaxResult logout() {
        return AjaxResult.success();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping("/userInfo")
    public AjaxResult userInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("name", user.getNickName());
        ajax.put("avatar", user.getAvatar());
        ajax.put("permissions", permissions);
        return ajax;
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    String appId = "wxe708705247441d41";
    String appSecret = "fd519a35bfe81221b6beacbc84dcd704";

    /**
     * 微信登录
     */
    @RequestMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody LoginBody loginBody) {


        return AjaxResult.success();
    }

}
